<template>
    <div class="mainBox">
        <div class="topBox">
            <span class="topTitle">公积金统计</span>
            <div class="topContent">
                <div ref="chartRef" style="width: 115px; height: 115px;margin-right: 47px;"></div>
                <div style="width: 100%;">
                    <div class="flex flex-1">
                        <div class="flex flex-1" style="align-items: center;">
                            <div class="flex box-row-column num_kuai" @click="selectItem(0, 1)"
                                :class="{ checked: checkedStatuslist[0] == 1 }"
                                :style="{ backgroundColor: checkedStatuslist[0] == 1 ? '#1864f2' : 'transparent' }">
                                <div class="zi3 y1"><span>正常存缴</span></div>
                                <div class="zi_num">{{ fundTotalData.zc }}</div>
                            </div>
                            <div class="flex box-row-column num_kuai" @click="selectItem(1, 0)"
                                :class="{ checked: checkedStatuslist[1] == 1 }"
                                :style="{ backgroundColor: checkedStatuslist[1] == 1 ? '#fe5c55' : 'transparent' }">
                                <div class="zi3 y2"><span>未存缴</span></div>
                                <div class="zi_num">{{ fundTotalData.wcj }}</div>
                            </div>
                            <div class="flex box-row-column num_kuai" @click="selectItem(2, 2)"
                                :class="{ checked: checkedStatuslist[2] == 1 }"
                                :style="{ backgroundColor: checkedStatuslist[2] == 1 ? '#2ad4ae' : 'transparent' }">
                                <div class="zi3 y3"><span>已停缴</span></div>
                                <div class="zi_num">{{ fundTotalData.ytj }}</div>
                            </div>
                            <div class="flex box-row-column num_kuai" @click="selectItem(3, 4)"
                                :class="{ checked: checkedStatuslist[3] == 1 }"
                                :style="{ backgroundColor: checkedStatuslist[3] == 1 ? '#ff7b43' : 'transparent' }">
                                <div class="zi3 y4"><span>存缴预警</span></div>
                                <div class="zi_num">{{ fundTotalData.cjyj }}</div>
                            </div>
                            <div class="flex box-row-column num_kuai" @click="selectItem(4, 5)"
                                :class="{ checked: checkedStatuslist[4] == 1 }"
                                :style="{ backgroundColor: checkedStatuslist[4] == 1 ? '#9188e5' : 'transparent' }">
                                <div class="zi3 y5"><span>停缴预警</span></div>
                                <div class="zi_num">{{ fundTotalData.tjyj }}</div>
                            </div>
                            <div class="flex box-row-column num_kuai" @click="selectItem(5, 3)"
                                :class="{ checked: checkedStatuslist[5] == 1 }"
                                :style="{ backgroundColor: checkedStatuslist[5] == 1 ? '#e5c388' : 'transparent' }">
                                <div class="zi3 y6"><span>异常存缴预警</span></div>
                                <div class="zi_num">{{ fundTotalData.yccj }}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="bottomBox">
            <div class="bottomTopBox">
                <span class="bottomTitle">公积金管理</span>
                <div class="bottomRightBox">
                    <el-popover placement="bottom">
                        <template #reference>
                            <el-button class="btnItem1">批量导入</el-button>
                        </template>
                        <div style="display: flex;flex-direction: column;align-items: center;">
                            <el-upload ref="uploadRef" class="upload-demo"
                                action="https://demo-api.niuyuwang.com/hr/import/fund_import" :limit="1"
                                :headers="{ token: token }" name="excel" :show-fileList="false"
                                :on-success="handleSuccess">
                                <el-button class="btnItem2">上传文件</el-button>
                            </el-upload>
                            <el-button class="btnItem2" style="margin-left: 0;margin-top: 6px;"
                                @click.stop="downloadFile">下载模版</el-button>
                        </div>
                    </el-popover>
                    <el-button class="btnItem1" :disabled="checklist.length == 0" @click="openHandle1">批量登记</el-button>
                    <el-button class="btnItem2" color="#01509f" @click="exports">导出</el-button>
                </div>
            </div>
            <div class="bottomListBox">
                <el-form ref="queryForm" :inline="true" label-width="100px" class="mt20" :model="queryParams">
                    <el-form-item label="员工状态：">
                        <el-select v-model="queryParams.job_status" placeholder="请选择状态" style="width: 200px;height: 36px;">
                            <el-option v-for="item in jobstatusoptions" :key="item.value" :label="item.name"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="员工姓名">
                        <el-input v-model="queryParams.name" placeholder="请输入员工姓名" clearable style="width: 200px;height: 36px;" />
                    </el-form-item>
                    <el-form-item label="入职时间">
                        <el-date-picker style="width: 200px;height: 36px;" v-model="queryParams.hired_time" type="daterange"
                            range-separator="-" format="YYYY/MM/DD" value-format="YYYY-MM-DD" start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button style="width: 72px;height: 36px;font-size: 16px;" type="primary" size="mini" color="#01509f" @click="handleQuery">搜索</el-button>
                        <el-button style="width: 72px;height: 36px;font-size: 16px;" @click="reset">重置</el-button>
                    </el-form-item>
                </el-form>
                <el-table :data="list" border @selection-change="handleSelectionChange" v-loading="loading"
                    element-loading-background="rgba(0, 0, 0, 0.5)" element-loading-text="加载中..."
                    header-row-class-name="table-header">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="员工" align="center" key="name" prop="name" />
                    <el-table-column label="个人客户号/账号" width="190"  align="center" key="fund_account" prop="fund_account" />
                    <el-table-column label="存缴状态" align="center" key="fund_status" prop="fund_status">
                        <template #default="scope">
                            <span v-if="scope.row.fund_status == 0">未存缴</span>
                            <span v-if="scope.row.fund_status == 1">正常存缴</span>
                            <span v-if="scope.row.fund_status == 2">已停缴</span>
                            <span v-if="scope.row.fund_status == 3">异常存缴</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="身份证号" width="200" align="center" key="id_card" prop="id_card" />
                    <el-table-column label="员工状态" align="center" key="job_status" prop="job_status">
                        <template #default="scope">
                            <span v-if="scope.row.job_status == 1">试用</span>
                            <span v-if="scope.row.job_status == 2">正式</span>
                            <span v-if="scope.row.job_status == 3">待离职</span>
                            <span v-if="scope.row.job_status == 4">离职</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="入职时间" align="center" key="hired_time" prop="hired_time" />
                    <el-table-column label="离职时间" align="center" key="resign_time" prop="resign_time" />
                    <el-table-column label="存缴时间" align="center" key="fund_time" prop="fund_time" />
                    <el-table-column label="停缴时间" align="center" key="fund_stop_time" prop="fund_stop_time" />

                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right"
                        width="230">
                        <template #default="scope">
                            <el-button style="font-size: 16px;" text icon="Document" @click="openHandle(scope.row)">登记</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <Pagination :total="total" :current-page="pageInfo.page" :page-size="pageInfo.limit"
                    @pagination-change="handlePaginationChange" />
            </div>
        </div>
        <el-dialog v-model="open" title="登记" width="538" :before-close="handleClose">
            <el-form ref="ruleFormRef" label-position="right" label-width="130px" :model="form" class="form-inline">
                <el-form-item class="" label="员工：">
                    <span v-if="!is_batch">{{ form.name }}</span>
                    <span v-if="is_batch">已选择{{ checklist.length }}人</span>
                </el-form-item>
                <el-form-item class="" label="个人客户号/账号：" v-if="!is_batch">
                    <el-input v-model="form.fund_account" type="text" placeholder="个人客户号/账号" />
                </el-form-item>
                <el-form-item class="" label="存缴状态：">
                    <el-radio-group v-model="form.fund_status">
                        <el-radio :value="0">未存缴</el-radio>
                        <el-radio :value="1">正常存缴</el-radio>
                        <el-radio :value="2">已停缴</el-radio>
                        <el-radio :value="3">异常存缴</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item class="" label="参缴时间：" v-if="form.fund_status == 1">
                    <el-date-picker v-model="form.fund_time" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                        placeholder="请选择参缴时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item class="" label="停缴时间：" v-if="form.fund_status == 2">
                    <el-date-picker v-model="form.fund_stop_time" type="date" format="YYYY/MM/DD"
                        value-format="YYYY-MM-DD" placeholder="请选择停缴时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item class="" label="备注：">
                    <el-input v-model="form.fund_desc" style="width: 309px;height: 51px;" :rows="2" type="textarea"
                        placeholder="备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="small" @click="cancel">取消</el-button>
                    <el-button type="primary" color="#01509f" size="small" @click="changeInfo">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed } from '@/TUIKit/adapter-vue';
import Pagination from "@/components/Pagination.vue";
import type { ElMessage, ElMessageBox, UploadProps } from 'element-plus'
import { user_list } from "@/api/cf";
import { fund_handle, fundExport, fundTotal } from "@/api/xl";
import { exportFile } from '@/utils/format'
import * as echarts from "echarts";
const chartRef = ref(null);
const uploadRef = ref(null)
const queryParams = ref({ name: "", hired_time: "", job_status: "", fund_status: "" });
const pageInfo = ref({ page: 1, limit: 10 });
const loading = ref(false);
const open = ref(false)
const is_batch = ref(false)
const total = ref(0);
const form = ref({});
const fundTotalData = ref({});
const list = ref([]);
const token = localStorage.getItem('token')
const checklist = ref([]);
const checkedStatuslist = ref([0, 0, 0, 0, 0, 0]);
const jobstatusoptions = ref([
    { value: '1', name: "试用" },
    { value: '2', name: "正式" },
    { value: '3', name: "待离职" },
    { value: '4', name: "离职" },
]);
let chartInstance = null;
onMounted(() => {
    getFund();
    // 监听窗口大小变化事件以支持响应式
    window.addEventListener("resize", resizeChart);
    getuser_list();
});
onBeforeUnmount(() => {
    window.removeEventListener("resize", resizeChart);
    chartInstance?.dispose(); // 销毁 echarts 实例
});
const getFund = () => {
    fundTotal().then(res => {
        fundTotalData.value = res.data;
        initChart();
    });
}
const handleClose = (done: () => void) => {
    done()
}
const selectItem = (index, status) => {
    queryParams.value.fund_status = status;
    checkedStatuslist.value = [0, 0, 0, 0, 0, 0];
    checkedStatuslist.value.splice(index, 1, 1);
    handleQuery()
}
const openHandle = (row) => {
    form.value = JSON.parse(JSON.stringify(row))
    form.value.fund_status = 3;
    open.value = true
}
const openHandle1 = () => {
    form.value.fund_status = 3;
    open.value = true
    is_batch.value = true
}
const cancel = () => {
    open.value = false;
    resetForm()
}
const resetForm = () => {
    form.value.name = "";
    form.value.fund_account = "";
    form.value.fund_status = "";
    form.value.fund_time = "";
    form.value.fund_stop_time = "";
    form.value.fund_desc = "";
}
const changeInfo = () => {
    if (is_batch.value) {
        let group_ids = computed(() => checklist.value.map(item => item.id));
        form.value.id = group_ids;
    }
    if (form.value.job_status == 2 && form.value.fund_status == 2) {
        ElMessageBox.confirm(
            '该员工为正式状态，请确认是否不再为其存缴，若未按照约定为其存缴存在法律风险！',
            '确认提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                fund_handle({
                    id: form.value.id,
                    fund_status: form.value.fund_status,
                    fund_time: form.value.fund_time,
                    fund_stop_time: form.value.fund_stop_time,
                    fund_desc: form.value.fund_desc,
                    fund_account: form.value.fund_account,
                }).then(res => {
                    ElMessage({
                        message: res.msg,
                        grouping: true,
                        type: "success",
                    });
                    open.value = false
                    resetForm()
                    handleQuery()
                });
            })
            .catch(() => {

            })
    } else {
        fund_handle({
            id: form.value.id,
            fund_status: form.value.fund_status,
            fund_time: form.value.fund_time,
            fund_stop_time: form.value.fund_stop_time,
            fund_desc: form.value.fund_desc,
            fund_account: form.value.fund_account,
        }).then(res => {
            ElMessage({
                message: res.msg,
                grouping: true,
                type: "success",
            });
            open.value = false
            resetForm()
            handleQuery()
        });
    }
    getFund()
}
const resizeChart = () => {
    chartInstance?.resize();
};
const handleSelectionChange = (val) => {
    checklist.value = val;
    console.log(checklist.value.length)
}
const handlePaginationChange = ({ page, size }: { page: number; size: number }) => {
    pageInfo.value.page = page;
    pageInfo.value.limit = size;
    getuser_list()
};
const reset = () => {
    queryParams.value.name = "";
    queryParams.value.hired_time = "";
    queryParams.value.job_status = "";
    queryParams.value.fund_status = "";
    checkedStatuslist.value = [0, 0, 0, 0, 0, 0];
    getuser_list();
};
const handleQuery = () => {
    pageInfo.value.page = 1;
    pageInfo.value.limit = 10;
    list.value = [];
    getuser_list();
};

const downloadFile = (row) => {
    const url = 'https://niuyuwang.oss-cn-shanghai.aliyuncs.com/uploads/20250703/uploads/20250703/公积金导入模板_20250703094534.xlsx'; // 替换为实际文件 URL
    const a = document.createElement('a');
    a.href = url;
    a.download = row.filename; // 自定义下载文件名
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    console.log(response.data[0])
    uploadRef.value!.clearFiles()
    ElMessage({
        message: response.data[0],
        type: 'warning',
    })
}

const exports = () => {
    ElMessageBox.confirm(
        '是否确认导出所有数据项?',
        '导出',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            fundExport({
                ...queryParams.value
            }).then(res => {
                exportFile(res, '公积金.xlsx')
            });
        })
        .catch(() => {

        })
}

const getuser_list = () => {
    user_list({ page: pageInfo.value.page, limit: pageInfo.value.limit, ...queryParams.value }).then(res => {
        console.log(res);
        list.value = res.data;
        total.value = res.count;
    });
}
const initChart = () => {
    if (chartRef.value) {
        // 初始化 echarts 实例
        chartInstance = echarts.init(chartRef.value, null, {
            width: 115, // 设置宽度
            height: 115, // 设置高度
        });

        // 配置项
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)',
                position: 'right'
            },
            color: ['#1864f2', '#fe5c55', '#2ad4ae', '#ff7b43', '#9188e5', '#e5c388'],
            series: [
                {
                    name: "公积金统计",
                    type: "pie", // 设置图表类型为饼图（环形图）
                    radius: ["70%", "90%"], // 设置外半径和内半径，实现环形图效果
                    avoidLabelOverlap: false, // 避免标签重叠
                    label: {
                        show: false, // 是否显示标签（如果要显示百分比，可以设置为true并在formatter中格式化）
                        position: "center", // 标签的位置，默认为'top'，此处设置为'center'便于显示百分比标签
                    },
                    emphasis: {
                        // 高亮的样式设置
                        label: {
                            show: true, // 高亮时显示标签
                            fontSize: "12", // 字体大小调整，便于显示百分比数值等详细信息
                            fontWeight: "bold", // 字体加粗显示高亮部分信息
                        },
                    },
                    labelLine: {
                        // 标签的视觉引导线样式设置，默认为直线，此处不设置即为直线效果，可根据需要调整样式如颜色等。
                        show: false, // 是否显示引导线（在某些情况下可能需要隐藏引导线）
                    },
                    data: [
                        { value: fundTotalData.value.zc, name: "正常存缴" },
                        { value: fundTotalData.value.wcj, name: "未存缴" },
                        { value: fundTotalData.value.ytj, name: "已停缴" },
                        { value: fundTotalData.value.cjyj, name: "存缴预警" },
                        { value: fundTotalData.value.tjyj, name: "停缴预警" },
                        { value: fundTotalData.value.yccj, name: "异常存缴预警" },
                    ],
                },
            ],
        };

        // 使用配置项渲染图表
        chartInstance.setOption(option);
    }
}
</script>

<style lang="scss" scoped>
.el-table {
    font-size: 16px;
    /* 默认大小 */
}

/* 设置表头文字 */
.el-table th {
    font-size: 18px;
}

/* 设置表格内容文字 */
.el-table td {
    font-size: 16px;
}

.mainBox {
    width: 100%;
    height: 100%;
    overflow-y: scroll;
    // padding: 22px;
    // box-sizing: border-box;

    .topBox {
        background-color: #fff;
        border-radius: 12px;
        padding: 17px;
        box-sizing: border-box;

        .topTitle {
            font-size: 20px;
            font-weight: bolder;
            color: #333;
        }

        .topContent {
            display: flex;
            align-items: flex-start;
            width: 100%;
            padding: 17px 41px 0 41px;
            box-sizing: border-box;

            .zi3 {
                font-size: 16px;
            }

            .num_kuai {
                // width: 30%;
                margin-top: 10px;
                margin-right: 98px;
                text-align: center;
                cursor: pointer;
                transition: background-color 0.8s ease, transform 0.8s ease;
                will-change: background-color;
            }

            .checked {
                color: #fff;
                border-radius: 6px;
                padding: 6px 10px;
                width: 92px;
                height: 64px;
                box-sizing: border-box;

                .y1::before {
                    display: none;
                }

                .y2::before {
                    display: none;
                }

                .y3::before {
                    display: none;
                }

                .y4::before {
                    display: none;
                }

                .y5::before {
                    display: none;
                }

                .y6::before {
                    display: none;
                }
            }

            .zi_num {
                font-size: 24px;
                font-weight: bold;
            }

            .y1::before {
                content: "";
                /* 使用空内容 */
                display: inline-block;
                /* 使元素为内联块元素 */
                width: 10px;
                /* 圆点宽度 */
                height: 10px;
                /* 圆点高度 */
                border-radius: 50%;
                /* 创建圆形 */
                background-color: #1864f2;
                /* 圆点颜色 */
                margin-right: 5px;
                /* 圆点和文本之间的间距 */
                /* 圆点和文本之间的间距 */
            }

            .y2::before {
                content: "";
                /* 使用空内容 */
                display: inline-block;
                /* 使元素为内联块元素 */
                width: 10px;
                /* 圆点宽度 */
                height: 10px;
                /* 圆点高度 */
                border-radius: 50%;
                /* 创建圆形 */
                background-color: #fe5c55;
                /* 圆点颜色 */
                margin-right: 5px;
                /* 圆点和文本之间的间距 */
                /* 圆点和文本之间的间距 */
            }

            .y3::before {
                content: "";
                /* 使用空内容 */
                display: inline-block;
                /* 使元素为内联块元素 */
                width: 10px;
                /* 圆点宽度 */
                height: 10px;
                /* 圆点高度 */
                border-radius: 50%;
                /* 创建圆形 */
                background-color: #2ad4ae;
                /* 圆点颜色 */
                margin-right: 5px;
                /* 圆点和文本之间的间距 */
                /* 圆点和文本之间的间距 */
            }

            .y4::before {
                content: "";
                /* 使用空内容 */
                display: inline-block;
                /* 使元素为内联块元素 */
                width: 10px;
                /* 圆点宽度 */
                height: 10px;
                /* 圆点高度 */
                border-radius: 50%;
                /* 创建圆形 */
                background-color: #ff7b43;
                /* 圆点颜色 */
                margin-right: 5px;
                /* 圆点和文本之间的间距 */
                /* 圆点和文本之间的间距 */
            }

            .y5::before {
                content: "";
                /* 使用空内容 */
                display: inline-block;
                /* 使元素为内联块元素 */
                width: 10px;
                /* 圆点宽度 */
                height: 10px;
                /* 圆点高度 */
                border-radius: 50%;
                /* 创建圆形 */
                background-color: #9188e5;
                /* 圆点颜色 */
                margin-right: 5px;
                /* 圆点和文本之间的间距 */
                /* 圆点和文本之间的间距 */
            }

            .y6::before {
                content: "";
                /* 使用空内容 */
                display: inline-block;
                /* 使元素为内联块元素 */
                width: 10px;
                /* 圆点宽度 */
                height: 10px;
                /* 圆点高度 */
                border-radius: 50%;
                /* 创建圆形 */
                background-color: #e5c388;
                /* 圆点颜色 */
                margin-right: 5px;
                /* 圆点和文本之间的间距 */
                /* 圆点和文本之间的间距 */
            }
        }
    }

    .bottomBox {
        background-color: #fff;
        border-radius: 12px;
        padding: 17px;
        box-sizing: border-box;
        margin-top: 22px;

        .bottomTopBox {
            padding-bottom: 18px;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #eaeaea;

            .bottomTitle {
                font-size: 20px;
                color: #333;
                font-weight: bolder;
                flex: 1;
            }

            .bottomRightBox {
                display: flex;
                align-items: center;

                .btnItem1 {
                    border-radius: 6px;
                    width: 108px;
                    height: 36px;
                    text-align: center;
                    line-height: 30px;
                    box-sizing: border-box;
                    font-size: 16px;
                    // color: #333;
                }

                .btnItem2 {
                    border: none;
                    border-radius: 6px;
                    width: 72px;
                    height: 36px;
                    text-align: center;
                    line-height: 30px;
                    box-sizing: border-box;
                    font-size: 16px;
                }
            }
        }
    }
}

:deep(.el-table__header) {
    .table-header {
        th {
            font-size: 16px;
            background: #f3f8fb;
            height: 53px;
            color: #6f7070;
            font-weight: normal;
        }
    }
}
</style>
